package main

import (
	"fmt"
	"log"
	"time"

	"github.com/androidsr/sc-go/sc"
	"github.com/androidsr/sc-go/scmd"
	"github.com/androidsr/sc-go/semail"
	"github.com/androidsr/sc-go/sminio"
	"github.com/androidsr/sc-go/syaml"
	"github.com/robfig/cron/v3"
)

var (
	shell *scmd.Command
	cfg   *Config
)

type Config struct {
	Sc         *syaml.ScInfo `yaml:"sc"`
	EmialTo    string        `yaml:"emialTo"`
	Cron       string        `yaml:"cron"`
	NameSuffix string        `yaml:"nameSuffix"`
	TaskDir    string        `yaml:"taskDir"`
	OutDir     string        `yaml:"outDir"`
}

func main() {
	log.SetFlags(log.Llongfile | log.LstdFlags)
	if cfg.Cron == "" {
		taskHandler()
	} else {
		c := cron.New(cron.WithSeconds())
		c.AddFunc(cfg.Cron, func() {
			taskHandler()
			fmt.Println("处理完成")
		})
		c.Start()
		select {}
	}
}

func init() {
	var err error
	cfg, err = syaml.LoadFile[Config]("sc-go.yaml")
	if err != nil {
		panic(err)
	}
	if cfg.Sc.Minio.Endpoint != "" {
		sminio.New(cfg.Sc.Minio)
	}
	shell = scmd.New(func(shell, output string) bool {
		log.Print(output)
		return true
	})
	semail.New(cfg.Sc.Email)
}

func taskHandler() {
	defer func() {
		recover()
	}()
	d, _ := time.ParseDuration("-24h")
	fileName := time.Now().Add(d).Format("20060102") + ".db.tar.gz"
	// 判断文件是否存在
	if !sc.IsFile(fileName) {
		err := sminio.DownloadFileDefault(cfg.Sc.Minio.BucketName, fileName, fileName)
		if err != nil {
			log.Println(cfg.Sc.Minio.BucketName, err)
			content := fmt.Sprintf("数据恢复验证处理：执行人：%s;\n 执行内容：%s;\n 执行时间：%s;\n 执行结果：%s",
				"系统自动执行", "恢复数据备份文件"+fileName, time.Now().Format("2006-01-02 15:04:05"), "下载备份文件失败")
			semail.SendEmail(cfg.Sc.Email.Username, cfg.EmialTo, "物流项目正式数据恢复测试验证", content)
			return
		}
	}
	shell.Command("tar xvzf " + fileName)
	e := shell.Command("sh task/db-restore.sh")
	if e != nil {
		content := fmt.Sprintf("数据恢复验证处理：执行人：%s;\n 执行内容：%s;\n 执行时间：%s;\n 执行结果：%s",
			"系统自动执行", "恢复数据备份文件"+fileName, time.Now().Format("2006-01-02 15:04:05"), "执行恢复测试脚本失败")
		semail.SendEmail(cfg.Sc.Email.Username, cfg.EmialTo, "物流项目正式数据恢复测试验证", content)
		return
	}

	content := fmt.Sprintf("数据恢复验证处理：执行人：%s;\n 执行内容：%s;\n 执行时间：%s;\n 执行结果：%s",
		"系统自动执行", "恢复数据备份文件"+fileName, time.Now().Format("2006-01-02 15:04:05"), "恢复测试处理成功")
	semail.SendEmail(cfg.Sc.Email.Username, cfg.EmialTo, "物流项目正式数据恢复测试验证", content)
}
